package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.SensorBasePropertyEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

/**
 * 获取传感器基础属性的反馈信息
 * 
 * @author yuzhantao
 *
 */
public class GetSensorBasePropertyReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private final static String ACTION_CODE = "GetSensorBasePropertyReturn";
	private final static Logger logger = LogManager.getLogger(GetSensorBasePropertyReturnHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if (t.getCommandCode() == 0x02) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		SensorBasePropertyEntity sensorProperty = new SensorBasePropertyEntity();
		// 设置设备编号
		sensorProperty.setDeviceAddress(t.getDeviceAddress());
		// 设置传感器通道号
		sensorProperty.setSensorChannelNumber(t.getDatas()[0]);
		// 设置传感器Id
		sensorProperty.setSensorId(ByteUtil.byteArrayToInt(t.getDatas(), 1));
		// 设置传感器版本
		sensorProperty.setSensorVersion(t.getDatas()[5]);
		// 设置气体Id
		sensorProperty.setGasId(t.getDatas()[6]);
		// 设置气体单位Id
		sensorProperty.setGasUnitId(t.getDatas()[7]);
		// 设置小数位
		sensorProperty.setDecimalDigits(t.getDatas()[8]);
		// 设置量程
		sensorProperty.setRange(ByteUtil.byteArrToShort(t.getDatas(), 9));

		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(sensorProperty);

		switch (t.getCommandRunStatus()) {
		case 0:
			message.setIsSuccess(true);
			break;
		case 2:
			message.setIsSuccess(false);
			message.setErrorMessage("通道号无效");
			break;
		case 3:
			message.setIsSuccess(false);
			message.setErrorMessage("通道未使能");
			break;
		case 4:
			message.setIsSuccess(false);
			message.setErrorMessage("通道已失效");
			break;
		default:
			message.setIsSuccess(false);
			message.setErrorMessage("未知信息");
			break;
		}
		String json = JSON.toJSONString(message);
		topicSender.send(json);
		logger.info("发送[{}]到MQ完成:{}", "获取传感器参数反馈信息", json);

		return null;
	}

}
